package com.example.demo.config.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 统一错误返回;
 */
@ControllerAdvice
public class GloablExceptionHandler {
    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Exception handleException(Exception e) {
        if(e instanceof PropertyReferenceException){  //实体类字段错误
            e = new WebException(ErrorCode.WRONG_COLUMN_NAME,
                    "字段名称匹配失败，请检查字段是否正确。"+((PropertyReferenceException) e).getMessage());
        }else if(e instanceof MissingServletRequestParameterException){ //缺少必要参数
            e = new WebException(ErrorCode.MISSING_PARAMETER,
                    "缺少参数："+((MissingServletRequestParameterException) e).getMessage());
        }

        return e;
    }
}
